"""Expose CKI service metrics."""
import argparse
import os

from cki_lib import cronjob
from cki_lib import misc
from cki_lib import yaml
from cki_lib.logger import get_logger
from cki_lib.metrics import prometheus_init

from . import metrics

LOGGER = get_logger(__name__)
LOOP_PERIOD_S = misc.get_env_int('LOOP_PERIOD_S', 5)
METRICS_CONFIG = yaml.load(contents=os.environ.get('METRICS_CONFIG', '{}'))


def get_enabled_metrics():
    """Return enabled metrics."""
    default_enabled = METRICS_CONFIG.get('default_enabled', False)
    return [
        metric() for metric in metrics.ALL_METRICS
        if METRICS_CONFIG.get(f'{metric.__name__.lower()}_enabled', default_enabled)
    ]


def run(args: list[str] | None = None) -> None:
    """Loop and update metrics."""
    parser = argparse.ArgumentParser()
    parser.parse_args(args)

    prometheus_init()

    enabled_metrics = get_enabled_metrics()

    cronjob.run(enabled_metrics, LOOP_PERIOD_S)
